﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

using System.IO;

using System.Diagnostics;

namespace WindowsFormsApplication3
{
    class SkinColorDatabase
    {
        List<Color> skinColors; //list with RGB skin colors for drawing the skin color graph

        public SkinColorDatabase()
        {
            skinColors = new List<Color>();
        }

        public void LoadFromFile(string FileName)
        {
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            int nrOfElements = br.ReadInt32();
            for (int i = 0; i < nrOfElements; i++)
            {
                byte r = br.ReadByte();
                byte g = br.ReadByte();
                byte b = br.ReadByte();
                skinColors.Add(Color.FromArgb(r,g,b));
            }
            br.Close();
            fs.Close();
        }

        public void SaveToFile(string FileName)
        {
            FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(skinColors.Count);
            foreach (Color color in skinColors)
            {
                bw.Write(color.R);
                bw.Write(color.G);
                bw.Write(color.B);
            }
            bw.Close();
            fs.Close();
        }

        //add all the colors from an image if they aren't white and aren't already present in the database
        public void AddColorsFromImage(Image image)
        {
            Bitmap imageBitmap = new Bitmap(image);
            for(int i = 0; i < image.Size.Width; i++)
                for (int j = 0; j < image.Size.Height; j++)
                {
                    Color selectedPixelColor = imageBitmap.GetPixel(i, j);
                    if (!selectedPixelColor.Equals(Color.White))
                    {
                        if (!skinColors.Contains(selectedPixelColor))
                        {
                            skinColors.Add(selectedPixelColor);
                        }
                    }
                }

            Debug.Write("There are " + skinColors.Count + " colors identified in this image.\n");
        }

        public List<Color> SkinColors
        {
            get
            {
                return skinColors;
            }
            set
            {
                skinColors = value;
            }
        }
    }
}
